package org.ccay.async.processor;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Calendar;

import org.ccay.async.AsyncMessage;
import org.ccay.async.ContextAwareMessage;
import org.ccay.async.IMessageProcessor;
import org.ccay.core.exception.ApplicationException;
import org.ccay.core.exception.ExceptionHandler;
import org.ccay.core.request.IRequestContext;

/**
 * 异步消息线程名称处理器
 * @author chaowangbang
 */
public class ThreadNameInterceptProcessor implements IMessageProcessor {
	/** 
	 * 原始的Processor
	 */
	private IMessageProcessor processor;
	
	
	public ThreadNameInterceptProcessor(IMessageProcessor processor) {
		this.processor = processor;
	}
	
	@Override
	public void process(AsyncMessage message) throws ApplicationException {
		Thread currentThread = Thread.currentThread();
		//原始线程名称
		String originalThreadName = Thread.currentThread().getName();
		//新线程名称
		String newThreadName = getFriendlyThreadName(message);
		currentThread.setName(newThreadName);
		try{
			processor.process(message);
		}finally {
			//还原线程名称
			currentThread.setName(originalThreadName);
		}
	}
	
	
	protected String getFriendlyThreadName(AsyncMessage message) {
		StringBuilder name = new StringBuilder();
		name.append("AsyncMsg");
		name.append("("+message.getType()+") : ");
		try {
			name.append(InetAddress.getLocalHost().getHostName());
		} catch (UnknownHostException e) {
			ExceptionHandler.logException(e);
			name.append("unknowhost");
		}
		name.append("-");
		
		String currentUser = "Anonymous";
		if(message instanceof ContextAwareMessage) {
			// 从消息中获取上下文相关的信息
			IRequestContext rc = message.getContext(IRequestContext.class);
			currentUser = rc != null && rc.getUser() != null ? rc.getUser().getUserName() : "Anonymous";
		}
		
		name.append(currentUser);
		name.append("-");
		
		Calendar now = Calendar.getInstance();  
		name.append(now.get(Calendar.DAY_OF_MONTH));
		name.append("-");
		name.append(now.get(Calendar.HOUR_OF_DAY));
		name.append("-");
		name.append(now.get(Calendar.MINUTE));
		name.append("-");
		name.append(now.get(Calendar.SECOND));
		name.append("-");
		name.append(now.get(Calendar.MILLISECOND));
		name.append("-");
		name.append(Thread.currentThread().getId());
		return name.toString();
	}

}
